<template>
    <view class="pub_page pub_page_bg_big pub_header_padding pub_good_order">
        <pub-head headerName="good_order" :headerConfig="headerConfig"></pub-head>
        <pub-dialog v-show="dialogShow" :dialogConfig="dialogConfig" @dialogBack="dialogBack"></pub-dialog>
        <div class="good_order_box" v-if="goodInfo != ''">
            <div class="address_div" @click="$comFun.openWin('/pages/other/address', { openType: 2 })">
                <div class="lo_icon icon-font-basic icon-b-dingwei"></div>
                <div class="p_1" v-if="addressInfo == ''">选择地址</div>
                <div class="p_1" v-if="addressInfo != ''">{{ addressInfo.receiver }} <span class="mobile">{{
                        addressInfo.phone
                        }}</span></div>
                <div class="p_2" v-if="addressInfo != ''">{{ addressInfo.area }}{{ addressInfo.address }}</div>
                <div class="right_icon icon-font-basic icon-b-arrow-1-2"></div>
            </div>
            <div class="good_div">
                <div class="div_title">商品信息</div>
                <pub-image class="img" :src="goodInfo.coverImg"></pub-image>
                <div class="info">
                    <div class="title">
                        <div class="name">{{ goodInfo.goodsName }}</div>
                        <!-- <div class="sku" v-if="orderType == 1">{{ goodInfo.skuName }}</div> -->
                    </div>
                    <div class="price">
                        <span class="￥">￥</span> {{ goodInfo.sellPrice }}
                        <span class="kc">库存:{{ goodInfo.stock }}</span>
                    </div>
                </div>
                <div class="lis">
                    <div class="li">
                        <div class="left">购买数量</div>
                        <div class="right">
                            <div class="sub icon-font-basic icon-b-as-10" @click="numDeal('sub')"></div>
                            <div class="num">{{ buyNum }}</div>
                            <div class="add icon-font-basic icon-b-as-9" @click="numDeal('add')"></div>
                        </div>
                    </div>
                    <div class="li">
                        <div class="left">小计</div>
                        <div class="right right_1">￥{{ totalPrice }}</div>
                    </div>
                </div>
            </div>
            <div class="pay_div">
                <div class="div_title">支付方式</div>
                <div class="li" @click="payType = 2">
                    <div class="gwjf"></div>
                    抵用券支付
                    <text class="icon-font-basic icon-b-select-6" v-if="payType == 2"></text>
                </div>
                <div class="li" @click="payType = 1">
                    <text class="icon-font-app icon-a-zfb-3"></text> 支付宝支付
                    <text class="icon-font-basic icon-b-select-6" v-if="payType == 1"></text>
                </div>
            </div>
            <!-- <div class="pay_div" v-if="orderType == 3">
                <div class="div_title">寄售方式</div>
                <div class="li" @click="isConsignment = isConsignment==1?0:1">
                    是否寄售
                    <text class="icon-font-basic icon-b-select-6" v-if="isConsignment == 1"></text>
                </div>
            </div> -->
            <div class="bottom_div">
                <!-- <div class="txt" v-if="orderType == 3">共{{ buyNum }}件
                    <span class="span_1">合计：</span>
                    <span class="span_3">{{ totalPrice }}</span>
                    <span class="span_2">兑换券</span>
                </div> -->
                <div class="txt">共{{ buyNum }}件
                    <span class="span_1">合计：</span>
                    <span class="span_2">￥</span>
                    <span class="span_3">{{ totalPrice }}</span>
                </div>
                <div class="btn pub_btn" @click="toSubmit">提交订单</div>
            </div>
        </div>
    </view>
</template>

<script>
export default {
    data() {
        return {
            pagescrollTop: 0,
            headerConfig: {
                title: '生成订单',//标题栏内容
                left_type: 3,
            },

            goodInfo: '',

            payType: 2,// 1支付宝 2抵用券
            orderType: 0,//4拼团商品 10供应链商品  

            addressInfo: '',
            buyNum: 1,//购买数量

            dialogShow: false,
            dialogType: '',
            dialogConfig: {
                title: '提示',//标题栏内容
                content: ''
            },
        };
    },
    computed: {
        totalPrice() {
            return Math.round(this.buyNum * this.goodInfo.sellPrice * 100) / 100;
        }
    },
    onLoad(option) {
        console.log("===option",option);
        this.goodInfo = option.goodInfo ? JSON.parse(option.goodInfo) : '';
        // this.addressInfo = option.addressInfo ? JSON.parse(option.addressInfo) : '';
        // console.log(this.goodInfo);
        if (!option.orderType) return
        this.orderType = option.orderType;
        this.buyNum = option.buyNum || 1;

        const that = this;
        uni.$on('chooseAddressBack', function (data) {
            // console.log(data);
            that.addressInfo = data;
        })
    },
    beforeDestroy() {
        uni.$off('chooseAddressBack');
    },
    onPageScroll(res) {
        this.pagescrollTop = res.scrollTop;
    },
    methods: {
        dialogBack(data) {
            // console.log(data);
            this.dialogShow = false;
            if (data.key == 1 && this.dialogType === 'sureSubmit') {
                this.sureSubmit(this.dialogType)
            }
        },
        numDeal(type) {
            switch (type) {
                case 'sub':
                    if (this.buyNum > 1) this.buyNum--;
                    break;
                case 'add':
                    if (this.buyNum < this.goodInfo.stock) {
                        this.buyNum++;
                    }
                    break;
            }
        },
        toSubmit() {
            if (!this.addressInfo) {
                this.$comFun.toast('请选择地址');
                return;
            }
            this.dialogType = 'sureSubmit';
            this.dialogConfig = {
                title: '提示',//标题栏内容
                content: '是否确定提交订单？'
            }
            this.dialogShow = true;
        },
        async sureSubmit() {
            this.$comFun.openLoading();
            let types = {
                'payType_1': {
                    payWay: -1,
                    orderType: this.orderType,
                },
                'payType_2': {
                    payWay: 8,
                    orderType: this.orderType,
                }
            }
            const params = {
                addressId: this.addressInfo.id,
                ...types['payType_' + this.payType],
                items: [{
                    "spuId": this.goodInfo.id || this.goodInfo.spuId,
                    "skuId": this.goodInfo.id || this.goodInfo.skuId,
                    "buyNum": this.buyNum,
                    "sellPrice": this.goodInfo.sellPrice,
                    "costPrice": this.goodInfo.sellPrice,
                    "totalSellPrice": Math.round(this.buyNum * this.goodInfo.sellPrice * 100) / 100,
                }],
            }
            console.log('支付相关数据打印', params);
            const res_1 = await this.$request.post('payments/createOrder', params);
            console.log(res_1);
            if (res_1.code == 200) {
                if (this.payType === 1) {
                    this.toAliPay(res_1.result);
                } else if (this.payType === 2) {
                    this.$comFun.closeLoading();
                    this.$comFun.toast('支付成功');
                    setTimeout(() => {
                        uni.switchTab({
                            url: '/pages/home/index'
                        });
                    }, 1000);
                }
            } else {
                this.$comFun.toast(res_1.message);
                this.$comFun.closeLoading();
            }

            // this.$comFun.openLoading();
            // const res_1 = await this.$request.post('payments/createOrder', {
            //     addressId: this.addressInfo.id,
            //     payWay: this.payType,
            //     orderType: this.orderType,
            //     isConsignment: this.isConsignment,
            //     items: [{
            //         "spuId": this.goodInfo.spuId,
            //         "skuId": this.goodInfo.skuId,
            //         "buyNum": this.buyNum,
            //         "sellPrice": this.goodInfo.sellPrice,
            //         "costPrice": this.goodInfo.sellPrice,
            //         "totalSellPrice": this.totalPrice
            //     }],
            // });
            // console.log('支付相关数据打印');
            // console.log(res_1);
            // if (res_1.code == 200) {
            //     // if (this.payType == 1) {
            //     //     this.toAliPay(res_1.result);
            //     // }
            //     if (this.payType == 7 || this.payType == 8) {
            //         this.$comFun.closeLoading();
            //         this.$comFun.toast(this.orderType == 3 ? '兑换成功' : '支付成功');
            //         setTimeout(() => {
            //             uni.switchTab({
            //                 url: '/pages/index/index'
            //             });
            //         }, 1000);
            //     }
            //     // // 模拟回调
            //     // await this.$request.get('notify/imitate', {
            //     //     prepayNo: res_1.result.prepayNo,
            //     //     amount: this.totalPrice
            //     // });



            //     // const res_2 = await this.$request.post('payments/pay', {
            //     //     prepayNo: res_1.result.prepayNo,
            //     //     id: 6,
            //     // });
            //     // // console.log(res_2);
            //     // this.$comFun.closeLoading();
            //     // if (res_2.code == 200) {
            //     //     this.openWxMini(res_2.result);
            //     // } else {
            //     //     this.$comFun.toast(res_2.message);
            //     // }
            // } else {
            //     this.$comFun.toast(res_1.message);
            //     this.$comFun.closeLoading();
            // }
        },
        openWxMini(data) {
            const that = this;
            // #ifdef APP-PLUS
            uni.request({
                url: 'https://api2.payunk.com/index/xcxUrl', //仅为示例，并非真实接口地址。
                method: 'POST',
                data: {
                    appid: data.appid,
                    path: 'pages/index/index',
                    query: `type=3&name=goods&fee=${data.amount}&outTradeNo=${data.out_trade_no}&pay_type=${data.pay_type}&callback_url=${data.callback_url}&appid=${data.appid}&key=${data.key}`,
                    pay_type: data.pay_type,
                    sign: data.sign,
                },
                header: {},
                success: (res) => {
                    console.log({
                        appid: data.appid,
                        path: 'pages/index/index',
                        query: `type=3&name=goods&fee=${data.amount}&outTradeNo=${data.out_trade_no}&pay_type=${data.pay_type}&callback_url=${data.callback_url}&appid=${data.appid}&key=${data.key}`,
                        pay_type: data.pay_type,
                        sign: data.sign,
                    });
                    console.log(res.data);
                    if (res.data.code == 200) {
                        that.$store.dispatch('setIsWxMiniRecharge', true)
                        plus.runtime.openURL(res.data.url)
                    }
                }
            });
            return;
            // #endif
            // this.$comFun.toCopy(`pages/index/index?name=商品&fee=${data.fee}&outTradeNo=${data.outTradeNo}&pay_type=${data.pay_type}&callback_url=${data.callback_url}&appid=${data.appid}&key=${data.key}`);
            // #ifdef APP-PLUS
            // plus.share.getServices((s) => {
            //     let sweixin = {};
            //     for (let i = 0; i < s.length; i++) {
            //         let share = s[i];
            //         if (share.id === 'weixin') {
            //             sweixin = share
            //         }
            //     }
            //     //小程序参数，必填    
            //     let WeixinMiniProgramOptions = {
            //         id: 'gh_926622fbf84b',
            //         path: `pages/index/index?name=商品&fee=${data.fee}&outTradeNo=${data.outTradeNo}&pay_type=${data.pay_type}&callback_url=${data.callback_url}&appid=${data.appid}&key=${data.key}`,
            //     }
            //     if (sweixin) {
            //         this.$store.dispatch('setIsWxMiniRecharge', true)
            //         sweixin.launchMiniProgram(WeixinMiniProgramOptions);
            //     } else {
            //         this.$comFun.toast('当前环境不支持微信操作');
            //     }
            // }, function (e) {
            //     console.log("获取分享服务列表失败：" + e.message);
            // });
            // #endif
        },
        async toAliPay(pdata) {
            const res = await this.$request.post('payments/pay', {
                prepayNo: pdata.prepayNo,
                id: 9
            });
            console.log("chd====toAliPay", res);
            this.$comFun.closeLoading();
            if (res.code == 200 && res.result.payUrl) {
                // #ifdef APP-PLUS
                this.$store.dispatch('setIsZfbRecharge', true)
                // console.log('支付宝支付---1', res.result.path);
                plus.runtime.openURL(res.result.payUrl);
                // #endif
            } else {
                this.$comFun.toast(res.message || '获取支付信息失败，请稍后再试');
            }
        }
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/index.scss";
</style>
